package com.study.udf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * hmc:yyy,yyy:hmc
 * hmc yyy
 * yyy hmc
 */

public class MyUdtf2 extends GenericUDTF {

    List<String> list = new ArrayList<>();

    @Override
    public StructObjectInspector initialize(ObjectInspector[] argOIs) throws UDFArgumentException {
        //列名
        List<String> names = Arrays.asList("fields1","fields2");
        //类型校验
        List<ObjectInspector> fieldOIs = new ArrayList<>();
        fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        return ObjectInspectorFactory.getStandardStructObjectInspector(names, fieldOIs);
    }

    @Override
    public void process(Object[] args) throws HiveException {
        //异常过滤
        if (args.length==2)
            throw new HiveException("参数有误");
        String column = args[0].toString();
        String split = args[1].toString();
        String[] strings = column.split(split);
        for (String string : strings) {
            String[] columns = string.split(":");
            list.clear();
            list.add(columns[0]);
            list.add(columns[1]);
            super.forward(list);
        }
    }

    @Override
    public void close() throws HiveException {

    }
}
